package com.cmdi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: gaozb
 * @Date: 2021/9/3$ 15:50$
 * @Version: 1.0
 */
@Slf4j
public class JwtUtil {

    public static Integer getUserIdFromtoken(String token) {
        Integer uid = null;
        try {
            JSONObject jwtJson = JSON.parseObject(JwtHelper.decode(token).getClaims());
//            System.out.println(jwtJson);
            uid = jwtJson.getInteger("userinfo");
        } catch (Exception e) {
            log.error("错误原因", e);
            uid = -1;
        }
        return uid;
    }

    public static List<String> getPermissionsFromtoken(String token) {
        List<String> perms  = null;
        try {
            JSONObject jwtJson = JSON.parseObject(JwtHelper.decode(token).getClaims());
            String authorities = jwtJson.getString("authorities");
            if(StringUtils.isEmpty(authorities)) {
                return Collections.emptyList();
            }
            JSONArray objects = JSONArray.parseArray(authorities);
            if(objects == null) {
                return Collections.emptyList();
            }
            perms = objects.toJavaList(String.class);
        } catch (Exception e) {
            log.error("错误原因", e);
        }
        return perms;
    }

    private Boolean hasPerms(String token, String p) {
        if(token.startsWith("bearer")) {
            token = token.replace("bearer ", "");
        }
        List<String> permissionsFromtoken = JwtUtil.getPermissionsFromtoken(token);
        if(permissionsFromtoken != null) {
            return permissionsFromtoken.contains(p);
        }
        return false;
    }

    public static void main(String[] args) {
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicjIiLCJyMSJdLCJ1c2VyX25hbWUiOiJzb3VzdW8iLCJzY29wZSI6WyJhbGwiXSwiZXhwIjoxNjMwNjcyMTcxLCJhdXRob3JpdGllcyI6WyJhZG1pbl9iYW5rX3F1ZXJ5Iiwic3lzX3ByaXZpbGVnZV9xdWVyeSIsImJiYiJdLCJqdGkiOiI1NGFmOTBkMy0wOTZiLTRlYjYtOTEwZi04MTAwNWVjMmI4MzEiLCJ1c2VyaW5mbyI6MTAwLCJjbGllbnRfaWQiOiJpbm5lciJ9.dBKhjROOPMJ7gJZ7RQLBL5qL0Y5UjYKUidaLI07u0jc";
        getUserIdFromtoken(token);
        List<String> permissionsFromtoken = getPermissionsFromtoken(token);
        System.out.println(permissionsFromtoken);
    }
}